<template>
    <div class="blockContainer absolute left-[50%] translate-x-[-50%] w-full">
        <div class="block overflow-y-auto flex-1 mx-auto">
            <div class="mb-6">
                <h1 class="text-2xl font-bold">
                    {{ isReviewMode ? '审核题目' : (isEdit ? '题目详情' : '新增题目') }}
                </h1>
                <p class="text-gray-600 mt-2">
                    {{ isReviewMode ? '审核题目内容并决定是否通过' : (isEdit ? '修改题目信息和答案' : '创建新的题目') }}
                </p>
                <div v-if="isReviewMode && getChangesDescription()"
                    class="mt-2 p-2 bg-blue-50 border border-blue-200 rounded">
                    <p class="text-blue-700 text-sm">
                        <i class="icon-info-circle mr-1" />
                        检测到内容变更：{{ getChangesDescription() }}
                    </p>
                </div>

                <!-- 实时内容对比显示 -->
                <div v-if="isReviewMode" class="mt-4">
                    <div class="flex items-center justify-between mb-3">
                        <h3 class="text-lg font-semibold">内容对比</h3>
                        <div class="flex items-center gap-2">
                            <a-button v-if="getChangesDescription()" type="link" size="small" @click="resetToOriginal">
                                <i class="icon-undo mr-1" />
                                重置为原始内容
                            </a-button>
                            <a-button type="link" size="small" @click="showComparison = !showComparison">
                                {{ showComparison ? '收起' : '展开' }}
                                <i :class="showComparison ? 'icon-up' : 'icon-down'" class="ml-1" />
                            </a-button>
                        </div>
                    </div>
                    <div v-show="showComparison" class="grid grid-cols-1 lg:grid-cols-2 gap-4">
                        <!-- 原始内容 -->
                        <div class="border border-gray-200 rounded-lg p-4">
                            <h4 class="font-medium text-gray-700 mb-2 flex items-center">
                                <i class="icon-file-text mr-2" />
                                原始内容
                            </h4>
                            <div class="space-y-3 text-sm">
                                <div>
                                    <span class="font-medium text-gray-600">标题：</span>
                                    <span class="text-gray-800">{{ originalData.title || '无' }}</span>
                                </div>
                                <div>
                                    <span class="font-medium text-gray-600">领域：</span>
                                    <span class="text-gray-800">{{ originalData.domain || '无' }}</span>
                                </div>
                                <div>
                                    <span class="font-medium text-gray-600">难度：</span>
                                    <span class="text-gray-800">{{ originalData.difficulty || '无' }}</span>
                                </div>
                                <div>
                                    <span class="font-medium text-gray-600">描述：</span>
                                    <div class="text-gray-800 mt-1 p-2 bg-gray-50 rounded border">
                                        {{ originalData.description || '无' }}
                                    </div>
                                </div>
                                <div>
                                    <span class="font-medium text-gray-600">标准答案：</span>
                                    <div class="text-gray-800 mt-1 p-2 bg-gray-50 rounded border">
                                        {{ originalData.standardAnswer || '无' }}
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- 修改后内容 -->
                        <div class="border border-blue-200 rounded-lg p-4 bg-blue-50">
                            <h4 class="font-medium text-blue-700 mb-2 flex items-center">
                                <i class="icon-edit mr-2" />
                                修改后内容
                            </h4>
                            <div class="space-y-3 text-sm">
                                <div>
                                    <span class="font-medium text-blue-600">标题：</span>
                                    <span class="text-blue-800"
                                        :class="{ 'font-semibold': formData.title !== originalData.title }">
                                        {{ formData.title || '无' }}
                                    </span>
                                </div>
                                <div>
                                    <span class="font-medium text-blue-600">领域：</span>
                                    <span class="text-blue-800"
                                        :class="{ 'font-semibold': formData.domain !== originalData.domain }">
                                        {{ formData.domain || '无' }}
                                    </span>
                                </div>
                                <div>
                                    <span class="font-medium text-blue-600">难度：</span>
                                    <span class="text-blue-800"
                                        :class="{ 'font-semibold': formData.difficulty !== originalData.difficulty }">
                                        {{ formData.difficulty || '无' }}
                                    </span>
                                </div>
                                <div>
                                    <span class="font-medium text-blue-600">描述：</span>
                                    <div class="text-blue-800 mt-1 p-2 bg-white rounded border"
                                        :class="{ 'ring-2 ring-blue-300': formData.description !== originalData.description }">
                                        {{ formData.description || '无' }}
                                    </div>
                                </div>
                                <div>
                                    <span class="font-medium text-blue-600">标准答案：</span>
                                    <div class="text-blue-800 mt-1 p-2 bg-white rounded border"
                                        :class="{ 'ring-2 ring-blue-300': formData.standardAnswer !== originalData.standardAnswer }">
                                        {{ formData.standardAnswer || '无' }}
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <a-form ref="formRef" :model="formData" :rules="rules as any" layout="vertical" @finish="handleSubmit">
                <a-row :gutter="24">
                    <a-col :span="24">
                        <a-form-item name="title">
                            <template #label>
                                <span class="flex items-center">
                                    题目标题
                                    <span v-if="isReviewMode && formData.title !== originalData.title"
                                        class="ml-2 px-2 py-1 text-xs bg-orange-100 text-orange-600 rounded-full">
                                        已修改
                                    </span>
                                </span>
                            </template>
                            <a-input v-model:value="formData.title" placeholder="请输入题目标题" :maxlength="255" show-count />
                        </a-form-item>
                    </a-col>
                </a-row>

                <a-row :gutter="24">
                    <a-col :span="12">
                        <a-form-item name="domain">
                            <template #label>
                                <span class="flex items-center">
                                    题目领域
                                    <span v-if="isReviewMode && formData.domain !== originalData.domain"
                                        class="ml-2 px-2 py-1 text-xs bg-orange-100 text-orange-600 rounded-full">
                                        已修改
                                    </span>
                                </span>
                            </template>
                            <a-select v-model:value="formData.domain" placeholder="请选择题目领域">
                                <a-select-option v-for="item in DomainsENUM" :key="item.value" :value="item.value">
                                    {{ item.label }}
                                </a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                    <a-col :span="12">
                        <a-form-item name="difficulty">
                            <template #label>
                                <span class="flex items-center">
                                    题目难度
                                    <span v-if="isReviewMode && formData.difficulty !== originalData.difficulty"
                                        class="ml-2 px-2 py-1 text-xs bg-orange-100 text-orange-600 rounded-full">
                                        已修改
                                    </span>
                                </span>
                            </template>
                            <a-select v-model:value="formData.difficulty" placeholder="请选择题目难度">
                                <a-select-option v-for="item in difficultiesENUM" :key="item.value" :value="item.value">
                                    {{ item.label }}
                                </a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                </a-row>

                <a-row :gutter="24">
                    <a-col :span="24">
                        <a-form-item name="description">
                            <template #label>
                                <span class="flex items-center">
                                    题目描述
                                    <span v-if="isReviewMode && formData.description !== originalData.description"
                                        class="ml-2 px-2 py-1 text-xs bg-orange-100 text-orange-600 rounded-full">
                                        已修改
                                    </span>
                                </span>
                            </template>
                            <RichTextEditor v-model="formData.description" placeholder="请输入题目描述（可选）" :height="200" />
                        </a-form-item>
                    </a-col>
                </a-row>

                <a-row :gutter="24">
                    <a-col :span="24">
                        <a-form-item name="standardAnswer">
                            <template #label>
                                <span class="flex items-center">
                                    标准答案
                                    <span v-if="isReviewMode && formData.standardAnswer !== originalData.standardAnswer"
                                        class="ml-2 px-2 py-1 text-xs bg-orange-100 text-orange-600 rounded-full">
                                        已修改
                                    </span>
                                </span>
                            </template>
                            <RichTextEditor v-model="formData.standardAnswer" placeholder="请输入标准答案" :height="300" />
                        </a-form-item>
                    </a-col>
                </a-row>

                <!-- 审核原因输入框 -->
                <a-row v-if="isReviewMode" :gutter="24">
                    <a-col :span="24">
                        <a-form-item label="审核原因" name="reviewReason">
                            <a-textarea v-model:value="reviewReason" placeholder="请填写审核原因（如有修改内容，请详细说明）" :rows="3"
                                :maxlength="500" show-count />
                        </a-form-item>
                    </a-col>
                </a-row>

                <a-row :gutter="24">
                    <a-col :span="24">
                        <a-form-item>
                            <a-space>
                                <!-- 审核模式下的按钮 -->
                                <template v-if="isReviewMode">
                                    <a-button type="primary" @click="handleApprove" :loading="loading" size="large">
                                        通过审核
                                    </a-button>
                                    <a-button danger @click="handleReject" :loading="loading" size="large">
                                        拒绝审核
                                    </a-button>
                                    <a-button size="large" @click="handleCancel">
                                        返回
                                    </a-button>
                                </template>
                                <!-- 编辑模式下的按钮 -->
                                <template v-else>
                                    <a-button type="primary" html-type="submit" :loading="loading" size="large">
                                        {{ isEdit ? '更新题目' : '创建题目' }}
                                    </a-button>
                                    <a-button size="large" @click="handleCancel">
                                        取消
                                    </a-button>
                                </template>
                            </a-space>
                        </a-form-item>
                    </a-col>
                </a-row>
            </a-form>
        </div>
        <div v-if="isEdit" class="block w-[20%]">
            <div class="flex flex-col gap-2">
                <!-- {{ detail }} -->
                <StatusTag :status="detail?.reviewStatus" :reason="detail?.reviewReason" />
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { useTopics } from '../composables/useTopics'
import type { TopicDomain, Difficulty } from '~/types/topic.d.ts'
import { ReviewStatus } from '~/types/topic.d.ts'
import StatusTag from './components/statusTag.vue'
import RichTextEditor from '~/components/RichTextEditor.vue'
import { useUserStore } from '~/stores/user'
const userStore = useUserStore()

const route = useRoute()
const router = useRouter()
const { createTopic, updateTopic, getTopicById, reviewTopic, difficultiesENUM, DomainsENUM } = useTopics()

// 判断是编辑还是新增
const id = route.params.id as string
const isEdit = computed(() => id && id !== 'new')

// 判断是否是审核模式
const isReviewMode = computed(() => route.query.mode === 'review')

// 表单数据
const formData = ref({
    title: '',
    domain: undefined as TopicDomain | undefined,
    difficulty: undefined as Difficulty | undefined,
    description: '',
    standardAnswer: ''
})

// 表单验证规则
const rules = {
    title: [
        { required: true, message: '请输入题目标题', trigger: 'blur' },
        { min: 5, max: 255, message: '标题长度应在5-255个字符之间', trigger: 'blur' }
    ],
    domain: [
        { required: true, message: '请选择题目领域', trigger: 'change' }
    ],
    difficulty: [
        { required: true, message: '请选择题目难度', trigger: 'change' }
    ],
    standardAnswer: [
        { required: true, message: '请输入标准答案', trigger: 'blur' },
        { min: 10, max: 2000, message: '答案长度应在10-2000个字符之间', trigger: 'blur' }
    ]
}

const formRef = ref()
const loading = ref(false)
const detail = ref()
const reviewReason = ref('')
const showComparison = ref(true)

// 原始数据，用于比较变更
const originalData = ref({
    title: '',
    domain: undefined as TopicDomain | undefined,
    difficulty: undefined as Difficulty | undefined,
    description: '',
    standardAnswer: ''
})
// 如果是编辑模式，获取题目详情
const fetchTopicDetail = async () => {
    if (!isEdit.value) return

    try {
        loading.value = true
        const topic = await getTopicById(parseInt(id))
        if (topic) {
            const topicData = {
                title: topic.title,
                domain: topic.domain,
                difficulty: topic.difficulty,
                description: topic.description || '',
                standardAnswer: topic.standardAnswer || ''
            }
            formData.value = topicData
            // 保存原始数据用于比较变更
            originalData.value = { ...topicData }
            detail.value = topic
        }
    } catch (error) {
        console.error('获取题目详情失败:', error)
        message.error('获取题目详情失败')
    } finally {
        loading.value = false
    }
}

// 检测内容变更并生成变更记录
const getChangesDescription = () => {
    const changes: string[] = []

    if (formData.value.title !== originalData.value.title) {
        changes.push(`标题：${originalData.value.title} → ${formData.value.title}`)
    }

    if (formData.value.domain !== originalData.value.domain) {
        changes.push(`领域：${originalData.value.domain} → ${formData.value.domain}`)
    }

    if (formData.value.difficulty !== originalData.value.difficulty) {
        changes.push(`难度：${originalData.value.difficulty} → ${formData.value.difficulty}`)
    }

    if (formData.value.description !== originalData.value.description) {
        changes.push(`描述：${originalData.value.description || '无'} → ${formData.value.description || '无'}`)
    }

    if (formData.value.standardAnswer !== originalData.value.standardAnswer) {
        changes.push(`标准答案：${originalData.value.standardAnswer || '无'} → ${formData.value.standardAnswer || '无'}`)
    }

    return changes.length > 0 ? `内容变更：${changes.join('；')}` : ''
}

// 重置为原始内容
const resetToOriginal = () => {
    formData.value = { ...originalData.value }
    message.success('已重置为原始内容')
}

// 提交表单
const handleSubmit = async () => {
    try {
        loading.value = true

        if (isEdit.value) {
            // 更新题目
            await updateTopic(parseInt(id), {
                title: formData.value.title,
                domain: formData.value.domain!,
                difficulty: formData.value.difficulty!,
                description: formData.value.description,
                standardAnswer: formData.value.standardAnswer
            })
            message.success('题目更新成功')
        } else {
            // 创建题目
            await createTopic({
                title: formData.value.title,
                domain: formData.value.domain!,
                difficulty: formData.value.difficulty!,
                description: formData.value.description,
                standardAnswer: formData.value.standardAnswer,
                // submitterId: userStore.user?.id // 这里应该从用户状态获取
            })
            message.success('题目创建成功')
        }

        // 跳转回题目列表
        router.push('/StudyArea/Topics/MyTopic')
    } catch (error) {
        console.error('操作失败:', error)
        message.error(isEdit.value ? '题目更新失败' : '题目创建失败')
    } finally {
        loading.value = false
    }
}

// 审核通过
const handleApprove = async () => {
    try {
        loading.value = true

        // 检查是否有内容变更
        const changesDescription = getChangesDescription()
        let finalReviewReason = reviewReason.value.trim()

        // 如果有内容变更，将变更记录添加到审核原因中
        if (changesDescription) {
            if (finalReviewReason) {
                finalReviewReason = `${finalReviewReason}；${changesDescription}`
            } else {
                finalReviewReason = changesDescription
            }
        }

        // 如果没有填写审核原因，使用默认值
        if (!finalReviewReason) {
            finalReviewReason = '审核通过'
        }

        // 先更新题目内容（如果有变更）
        if (changesDescription) {
            await updateTopic(parseInt(id), {
                title: formData.value.title,
                domain: formData.value.domain!,
                difficulty: formData.value.difficulty!,
                description: formData.value.description,
                standardAnswer: formData.value.standardAnswer
            })
        }

        // 然后进行审核
        await reviewTopic(parseInt(id), {
            reviewStatus: ReviewStatus.APPROVED,
            reviewReason: finalReviewReason
        })

        message.success('题目审核通过')
        router.push('/StudyArea/Topics/Review')
    } catch (error) {
        console.error('审核失败:', error)
        message.error('审核失败')
    } finally {
        loading.value = false
    }
}

// 审核拒绝
const handleReject = async () => {
    // 检查是否填写了拒绝原因
    if (!reviewReason.value.trim()) {
        message.error('请填写拒绝原因')
        return
    }

    try {
        loading.value = true

        // 检查是否有内容变更
        const changesDescription = getChangesDescription()
        let finalReviewReason = reviewReason.value.trim()

        // 如果有内容变更，将变更记录添加到审核原因中
        if (changesDescription) {
            finalReviewReason = `${finalReviewReason}；${changesDescription}`
        }

        await reviewTopic(parseInt(id), {
            reviewStatus: ReviewStatus.REJECTED,
            reviewReason: finalReviewReason
        })

        message.success('题目已拒绝')
        router.push('/StudyArea/Topics/Review')
    } catch (error) {
        console.error('审核失败:', error)
        message.error('审核失败')
    } finally {
        loading.value = false
    }
}

// 取消操作
const handleCancel = () => {
    if (isReviewMode.value) {
        router.push('/StudyArea/Topics/Review')
    } else {
        router.push('/StudyArea/Topics/MyTopic')
    }
}

// 页面初始化
onMounted(() => {
    if (isEdit.value) {
        fetchTopicDetail()
    }
})

// 设置页面标题
useHead({
    title: isReviewMode.value ? '审核题目' : (isEdit.value ? '题目详情' : '新增题目')
})
</script>
